import axios from 'axios'
import { Notification, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { getUrlKey } from '@/utils/urlParse'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 600000
})
// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers['SourcePath'] = window.location.pathname + window.location.search
    }
    return config
  },
  error => {
    // console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
var flag = false
service.interceptors.response.use(res => {
  const code = res.data.code
    if (code === 401 && (res.data.msg !== '请求访问：/getInfo，认证失败，无法访问系统资源' || getUrlKey('token') !== undefined)) {
      logIn401()
    } else if (code === 900) {
      if (!flag) {
        MessageBox.alert(
          window.i18n?.t !== undefined ? window.i18n.t(res.data.msg) : res.data.msg,
          window.i18n?.t !== undefined ? window.i18n.t('系统提示') : '系统提示',
          {
            confirmButtonText: window.i18n?.t !== undefined ? window.i18n.t('去授权') : '去授权',
            type: 'warning',
            showClose: false
          }
        ).then(() => {
          flag = false
          window.location.href = '/license'
        })
      }
      flag = true
    } else if (code !== 200 && res.data.msg !== '请求访问：/getInfo，认证失败，无法访问系统资源') {
      if (res.data.msg) {
        Notification.info({
          title: window.i18n?.t !== undefined ? window.i18n.t(res.data.msg) : res.data.msg
        })
        return Promise.reject(res.data.msg)
      }
    } else {
      return res.data
    }
  },
  error => {
    if (error.message) {
      Notification.info({
        title: window.i18n?.t !== undefined ? window.i18n.t('请求超时,请检查网络配置!') : '请求超时,请检查网络配置!'
      })
    }
    return Promise.reject(error)
  }
)
window.service = service
export default service

/**
 * 401登录过期
 */
var msgCount = 2 // 登录超时提示n秒内不再提示
var reqCount = 0 // 401请求次数
var logCount = 0 // 密码错误失败次数
export function logIn401() {
  setTimeout(() => {
    reqCount = 0
  }, msgCount * 1000)
  // 失败3次. 返回到首页登录
  if (logCount >= 3) {
    store.dispatch('LogOut').then(() => { location.reload() })
  }
  if (reqCount === 0) {
    reqCount++
    MessageBox.confirm(
      window.i18n?.t !== undefined ? window.i18n.t('登录状态已过期，您可以继续留在该页面，或者重新登录') : '登录状态已过期，您可以继续留在该页面，或者重新登录',
      window.i18n?.t !== undefined ? window.i18n.t('系统提示') : '系统提示',
      {
        confirmButtonText: window.i18n?.t !== undefined ? window.i18n.t('重新登录') : '重新登录',
        cancelButtonText: window.i18n?.t !== undefined ? window.i18n.t('退出登录') : '退出登录',
        type: 'warning',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        closeOnHashChange: false
      }
    ).then(() => {
      if (document.location.pathname !== '/login') {
        MessageBox.prompt('', window.i18n.t('请输入密码'), {
          confirmButtonText: window.i18n.t('确定'),
          showCancelButton: false,
          inputErrorMessage: window.i18n.t('请输入密码'),
          inputType: 'password',
          closeOnClickModal: false,
          closeOnPressEscape: false,
          closeOnHashChange: false,
          inputValidator: (reason) => {
            if (reason === null || reason === '' || reason.trim().length < 1) {
              return window.i18n.t('密码不能为空')
            }
          }
        }).then(({ value }) => {
          var tenantCod = store.state.user.tenantCode
          if (tenantCod === undefined || tenantCod === null || tenantCod === '') {
            tenantCod = window.localStorage.getItem('tenantCode')
          }
          var loginInfo = {
            username: store.state.user.loginName,
            password: value,
            tenantCode: tenantCod
          }
          store.dispatch('Login', loginInfo).then(() => {
            // 关闭这盖层, 隐藏这盖层的class
            document.querySelectorAll('.el-loading-mask').forEach(item => {
              console.log(item)
              item.style.display = 'none'
            })
          }).catch(() => {
            logCount++
          })
        }).catch(() => {
        })
      } else {
        store.dispatch('LogOut').then(() => { location.reload() })
      }
    }).catch(() => {
      store.dispatch('LogOut').then(() => { location.reload() })
    })
  }
}
